package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.NcgDeviceWatch;
import com.sqx.modules.health.entity.Saihong;
import com.sqx.modules.health.service.INcgDeviceWatchService;
import com.sqx.modules.health.service.ISaihongService;
import com.sqx.modules.health.utils.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-05-31
 */

@Api(value = "", tags = "", description = "")
@RestController
@RequestMapping("/health/saihong")
public class SaihongController {
    @Autowired
    private ISaihongService saihongService;

    @Autowired
    private INcgDeviceWatchService deviceWatchService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result save(@RequestBody Saihong saihong) {
        return Result.success(saihongService.save(saihong));
    }

    // 根据ID删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable Integer id) {
        return Result.success(saihongService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(saihongService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll() {
        return Result.success(saihongService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(saihongService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") String deviceMac,
                           @RequestParam(required = false, defaultValue = "") Integer uid,
                           @RequestParam(required = false, defaultValue = "") String starttime,
                           @RequestParam(required = false, defaultValue = "") String endtime) {
        String deviceNo;
        if (uid != null && StringUtils.isBlank(deviceMac)) { // uid 有值 deviceMac为空
            // 根据用户id  查询用户绑定的设备
            QueryWrapper<NcgDeviceWatch> deviceWrapper = new QueryWrapper<>();
            deviceWrapper.eq("uid", uid);
            deviceWrapper.eq("type", 2);
            NcgDeviceWatch deviceWatch = deviceWatchService.getOne(deviceWrapper);
            if (deviceWatch == null) {
                return Result.error(Constants.CODE_500, "用户未绑定血压计!!!");
            }
            deviceNo = deviceWatch.getImei();
        } else if (ObjectUtil.isEmpty(uid) && StringUtils.isBlank(deviceMac)) { // 二者都为空
            return Result.error(Constants.CODE_500, "error");
        } else { // uid 为空 或者二者都不为空
            deviceNo = deviceMac;
        }
        // 默认查截止到目前的今天数据
        if (StringUtils.isBlank(starttime)) {
            DateTime dateTime = DateUtil.beginOfDay(new Date());
            starttime = dateTime.toString();
        }
        if (StringUtils.isBlank(endtime)) {
            endtime = DateUtil.date().toString();
            System.out.println(endtime);
        }
        List<Saihong> response = getResponse(deviceNo, starttime, endtime);

        Iterator<Saihong> iterator = response.iterator();
        // 过滤无效数据
        while (iterator.hasNext()) {
            Saihong next = iterator.next();
            String name = next.getIsValidName();
            if ("无效数据".equals(name)) {
                iterator.remove();
            }
        }
        Page<Saihong> page = new Page<>(pageNum, pageSize);
        page.setRecords(response);
        page.setTotal(response.size());
        return Result.success(page);
    }

    private List<Saihong> getResponse(String deviceMac, String starttime, String endtime) {
        try {
            String url = "http://taiyibp.tjtzkt.com/getBpDatas.aspx";
            // 设置请求体
            Map<String, Object> params = new HashMap<>();
            params.put("deviceMac", deviceMac);
            params.put("starttime", starttime);
            params.put("endtime", endtime);
            String param = JSON.toJSONString(params);
            String result = HttpUtils.sendPost(url, param);
            // 将获取到的返回数据转成 json格式数据
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            // 从json中获取data对应的数据
            List<Object> data = (List<Object>) jsonObject1.get("data");
            List<Saihong> saihongs = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                Saihong saihong = new Saihong();
                BeanUtil.copyProperties(data.get(i), saihong);
                saihongs.add(saihong);
            }
            return saihongs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}

